var issueID = null;
var text = [
  { load: '玩命加载中', end: '没有更多了哦', title: '发现', blank: '暂无新的发布内容', searchPlaceHolder: '请输入搜索关键词', warning:'本产品发布的信息具体内容不由本产品负责，若有疑问，可咨询客服' }, 
  { load: 'Loading', end: 'No more new projects', title: 'Find', blank: 'No more new projects', searchPlaceHolder: 'please enter keyword', warning:'This product is not responsible for the specific content of the information released by this product. If you have any questions, you can consult customer service'}
], 
tip_register = [
  { tip: '登录后才能发布项目噢~', confirm: '前往登录', cancel: '先看看', },
  { tip: 'Sign up to publish a project', confirm: 'Sign up', cancel: 'Not now',},
];
// TODO：发布新任务后切回主页，内容未及时更新
Page({
  data: {
    blankIcon: "/assets/module/blank.png",
    showMask: true,
    practices: [],
    loading: true,
    end: false,     // 是否已无记录
    search:''
  },

  onReady() {
    // wx.nav('/pages/module/index/finish/evaluate/evaluate?idPractice=3&evaluate=true');
    this.setData({
      text: text[wx.lang],
      theme: wx.theme,
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: "#ffffff",
    });
    this.showBroadcast()
  },

  onPullDownRefresh() {
    this.setData({
      loading: true,
    });
    wx.post('Practice.getPracticeList', {}, res => {
      wx.stopPullDownRefresh();
      wx.appData.practices = res.success ? res.data : [];
      if (!wx.appData.practices.length) {
        this.setData({
          loading: false,
        });
        return;
      };
      this.setData({
        practices: this.process(wx.appData.practices),
      });
      let array = [],
        endIndex = wx.appData.practices.length;
      if (endIndex > 5) endIndex = 5;
      for (let i = 0; i < endIndex; ++i)
        array.push('card[' + wx.appData.practices[i].idpractice + ']');
      // wx._slide_v(this, array, wx.system.height * .8, 0, () => {
      //   wx.slide_v(this, array, 0, 1, 0);
      this.setData({
        loading: false,
      });
      // })
    })
  },
  
  onShow() {
    this.bg_color = wx.createAnimation({
      duration: 1000,
      timingFunction: 'linear',
    });
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    });
    this.bg_color.opacity(0).step();
    this.setData({
      color: '#ffffff',
      bg: this.bg_color.export(),  // 构造 background 动画函数
    });
    wx.setNavigationBarTitle({
      title: text[wx.lang].title,
    })
    setTimeout(() => {
      this.setData({ 
        showMask: false,
        loading: false,
      });
    }, 800 * .8);
    if (typeof (wx.appData.practices) != 'object') return;
    this.setData({
      practices: this.process(wx.appData.practices),
    });
    let array = [],
      endIndex = wx.appData.practices.length;
    if (endIndex > 5) endIndex = 5;
    for (let i = 0; i < endIndex; ++i)
      array.push('card[' + wx.appData.practices[i].idpractice + ']');
    wx._slide_v(this, array, wx.system.height * .8, 0, () => {
      wx.slide_v(this, array, 0, 1, 0);
    })
   
  },
  //判断是否需要弹出广播弹窗
  async showBroadcast(){
    var idList=wx.getStorageSync('broadcastList') || [];  
    wx.appData.broadcast.forEach(broadcast => {
      console.log("索引：",idList.indexOf(broadcast))
      if(idList.indexOf(broadcast.id)==-1){
       //若缓存中不存在此条广播信息，则弹出弹窗
       wx.modal(broadcast.title,broadcast.content,
        "下次提醒", "知道了",
        null, "#07c160",
        //知道了回调
        () => { 
          idList.push(broadcast.id)
          wx.setStorageSync('broadcastList', idList)
         },
              //下次提醒回调
        () => {  },
      ); 
      }
    });
   
  },
  onReachBottom() {
    if (this.data.end) return;  // 判断是否还能获取数据
    this.setData({ loading: true });
    let id = this.data.practices[this.data.practices.length - 1].idpractice;
    wx.post('Practice.getPracticeList', { id: id }, res => {
      if (res.success) {
        this.setData({
          practices: wx.appData.practices.concat(this.process(res.data)),
        });
      } else {
        this.setData({ 
          end: true 
        });
      }
      this.setData({ loading: false });
    });
  },


  // 前端处理返回结果
  process(data) {
    for (let i = 0; i < data.length; i++) {
      let date = wx.formatTime(new Date(parseInt(data[i].gmtcreate) * 1e3), 'd-t').split(' '),
      _txt = data[i].description; // 多于大约 3 行时，后面文字截掉
      data[i].time = date[0] == wx.formatTime(new Date()) ? date[1] : date[0];
      data[i].text = _txt.length > 60 ? _txt.substring(0, 60) + '...' : data[i].text = _txt;
      data[i].endTime = wx.formatTime(new Date(parseInt(data[i].gmtend) * 1e3), '/');

    }
    return data;
  },


  swiperTap(e) {
    console.log(e);

  },

  cardTap(e) {
    console.log(e, this.data.practices)
    for (let i = 0; i < this.data.practices.length; ++i) {
      if (e.currentTarget.id == this.data.practices[i].idpractice) {
        wx.onHide(this, '../details/details?content=' + JSON.stringify(this.data.practices[i]))
        break;
      }
    }
  },

  add() {
    if (wx.appData.user.name) {
      wx.onHide(this, '../../module/index/release/release/release');
    } else {
      wx.modal(null, tip_register[wx.lang].tip,
        tip_register[wx.lang].cancel, tip_register[wx.lang].confirm,
        null, null,  // navigate to registration if not registered.
        () => { wx.nav('../register/register') }, () => { return; }
      );
    }
  },

  onShareAppMessage: function () {
    return wx.onShareAppMessage();
  }
})



function compareTime(date, output) {
  date = date.replace(/-/g, '/');   // - 替换为 /
  if (output = 'days') {
    date = date.split(' ')[0];
    var past = new Date(date), t = new Date(),
      char = ['', '一', '两', '三', '四', '五', '六'],
      now = new Date(([t.getFullYear(), t.getMonth() + 1, t.getDate()]).join('-')),
      days = parseInt((now.getTime() - past.getTime()) / (1000 * 60 * 60 * 24));
    if (output == 'day') return days;
    if (days > 364) return '一年前';
    if (days > 182) return '半年前';
    if (days > 29) return char[parseInt(days / 30)] + '个月前';
    if (days > 6) return char[parseInt(days / 7)] + '周前';
    if (days > 2) return char[days] + '天前';
    if (days > 1) return '前天';
    if (days > 0) return '昨天';
    return '今天'
  }
  var timestamp = new Date(date).getTime(),
    now = new Date().getTime(),
    sec = parseInt((now - timestamp) / 1000);
  if (output == 'm') return sec / 60;
  if (output == 'h') return sec / 3600;
  if (output == 'd') return sec / 3600 / 24;
  if (output == 'ms') return {
    m: parseInt(sec / 60),
    s: sec % 60,
  };
  if (output == 'hms') return {
    h: parseInt(sec / 3600),
    m: parseInt((sec % 3600) / 60),
    t: parseInt(sec / 60 % 60),
    s: sec % 3600,
  };
  return sec;
}